// pages/index/index.js

const config = require('../../config.js');
const app = getApp();

/**
 * 开机
 */
function openCarla(imei, token, openid) {
  console.log(imei);
  console.log(openid);
  console.log(token);
  wx.showToast({
    title: '正在开机...',
    icon: 'loading'
  });
  wx.request({
    //后台接口地址
    url: config.serverUrl + '/web/api/inner/opr/openCarla',
    data: {
      openid: openid,
      imei: imei,
      token: token,
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      wx.hideToast();
      if (res) {
        var respData = res.data;
        if (respData.code == '000000') {
          wx.navigateTo({
            url: "../carla/carla?qrData=" + encodeURIComponent(imei) + "&infoFlag=false"
          });
          console.log("开启成功!");
        } else if (respData.code == '000003') {
          wx.showToast({
            title: '请退出小程序再登录!',
            icon: 'none',
            duration: 5000
          })
        } else {
          console.log("**openCarla fail**");
          console.log(res)
          console.log("**openCarla fail**");
          wx.showToast({
            title: '开启失败!',
            icon: 'none',
            duration: 5000
          })
        }
      } else {
        console.log("**openCarla fail**");
        console.log(res)
        console.log("**openCarla fail**");
        wx.showToast({
          title: '开启失败!',
          icon: 'none',
          duration: 5000
        })
      }
    },
    fail: res => {
      wx.hideToast();
      console.log("**openCarla fail**");
      console.log(res)
      console.log("**openCarla fail**");
      wx.showToast({
        title: '开启失败!',
        icon: 'none',
        duration: 5000
      })
    }
  });
}

//绑定设备
function bindCarla(imei, token, openid) {
  console.log(imei);
  console.log(openid);
  console.log(token);
  wx.showToast({
    title: '正在绑定设备...',
    icon: 'loading'
  });
  wx.request({
    //后台接口地址
    url: config.serverUrl + '/web/api/inner/opr/bindCarla',
    data: {
      openid: openid,
      imei: imei,
      token: token,
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      wx.hideToast();
      if (res) {
        var respData = res.data;
        if (respData.code == '000000') {
          openCarla(imei, token, openid);
        } else if (respData.code == '000003') {
          wx.showToast({
            title: '请退出小程序再登录!',
            icon: 'none',
            duration: 5000
          })
        } else {
          console.log("**bindCarlafail**");
          console.log(res)
          console.log("**bindCarla fail**");
          wx.showToast({
            title: '绑定设备失败!',
            icon: 'none',
            duration: 5000
          })
        }
      } else {
        console.log("**bindCarla fail**");
        console.log(res)
        console.log("**bindCarla fail**");
        wx.showToast({
          title: '绑定设备失败!',
          icon: 'none',
          duration: 5000
        })
      }
    },
    fail: res => {
      wx.hideToast();
      console.log("********bindCarla fail********");
      console.log(res)
      console.log("*********bindCarla fail*******");
      wx.showToast({
        title: '绑定设备失败!',
        icon: 'none',
        duration: 5000
      })
    }
  });
}

function saveWeChatInfo(globalData) {
  wx.request({
    //后台接口地址
    url: config.serverUrl + '/web/api/inner/wechat/saveWeChatUserInfo',
    data: {
      openid: globalData.openid,
      nickName: globalData.userInfo.nickName,
      province: globalData.userInfo.province,
      city: globalData.userInfo.city,
      gender: globalData.userInfo.gender,
      country: globalData.userInfo.country,
      token: globalData.token
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      console.log(res)
    },
    fail: res => {
      wx.showToast({
        title: '保存失败！',
        icon: 'none',
        duration: 10000
      })
    }
  });
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    canShow: 0,
    tapTime: '',		// 防止两次点击操作间隔太快
    qrData: null,
    imgUrls: [{
      url: config.serverUrl + "/web/api/h1.jpg",
      key: "image1"
    }, {
      url: config.serverUrl + "/web/api/h2.jpg",
      key: "image2"
    }, {
      url: config.serverUrl + "/web/api/h3.jpg",
      key: "image3"
    }],

    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    showModal: true,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  needGasEvent: function (e) {
    if (this.data.canShow) {
      // if(1) {
      // 防止两次点击操作间隔太快
      var nowTime = new Date();
      if (nowTime - this.data.tapTime < 1000) {
        return;
      }
      var scanQrData = this.data.qrData;
      wx.showToast({
        title: '正在启动...',
        icon: 'loading'
      });
      // 只允许从相机扫码
      wx.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => {
          console.log(res)
          if (res.errMsg == 'scanCode:ok') {
            var scanQrData = res.result;
            if (scanQrData) {
              var openid = app.globalData.openid;
              var token = app.globalData.token;
              this.setData({
                qrData: scanQrData
              })
              wx.request({
                //后台接口地址
                url: config.serverUrl + '/web/api/inner/opr/checkBindAndOpen',
                data: {
                  openid: openid,
                  imei: scanQrData,
                  token: token,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: function (res) {
                  console.log(res);
                  if (res) {
                    var resultData = res.data;
                    console.log("------------------")
                    console.log(resultData)
                    if (resultData.code == '000000') {
                      //说明已经开机并绑定了设备
                      console.log("----openAndBind----")
                      wx.navigateTo({
                        url: "../device/device"
                      });
                      console.log("----openAndBind----")
                    } else if (resultData.code == '000012') {
                      //说明已经开机但是绑定设备的不是本用户 提示
                      wx.showToast({
                        title: '设备正在工作···',
                        icon: 'none',
                        duration: 5000
                      })
                    } else if (resultData.code == '000013') {
                      //说明没有开机，绑定设备的是本用户
                      console.log("----openCarla start----")
                      openCarla(scanQrData, app.globalData.token, app.globalData.openid);
                      console.log("----openCarla end----")
                    } else if (resultData.code == '000014') {
                      //说明没有开机，绑定设备的不是本用户  提示
                      wx.showToast({
                        title: '设备已经绑定了其他用户',
                        icon: 'none',
                        duration: 5000
                      })
                    } else if (resultData.code == '000015') {
                      //没有开机 也没有绑定
                      //先绑定 再开机
                      bindCarla(scanQrData, app.globalData.token, app.globalData.openid);
                    } else if (resultData.code == '000003') {
                      wx.showToast({
                        title: '请退出小程序在登录!',
                        icon: 'none',
                        duration: 5000
                      })
                    } else {
                      wx.showToast({
                        title: '服务器失败!',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  } else {
                    wx.showToast({
                      title: '检查设备失败！',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                },
                fail: res => {
                  wx.showToast({
                    title: '请求失败！',
                    icon: 'none',
                    duration: 2000
                  })
                }
              });
            } else {
              wx.showToast({
                title: '扫一扫失败！',
                icon: 'none',
                duration: 2000
              })
            }
          } else {
            wx.showToast({
              title: '扫一扫失败！',
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: (res) => {
          wx.showToast({
            title: '扫一扫失败！',
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后再试。',
        showCancel: false
      });
    }
  },
  moreEvent: function () {
    wx.showToast({
      title: '敬请期待！',
      icon: 'none',
      duration: 2000
    })
  },
  doShutdown: function () {
    //我的设备列表界面
    wx.navigateTo({
      url: "../device/device"
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (!wx.createLivePlayerContext) {
      setTimeout(function () {
        wx.showModal({
          title: '提示',
          content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后再试。',
          showCancel: false
        });
      }, 0);
    } else {
      // 版本正确，允许进入
      this.data.canShow = 1;
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log("onShareAppMessage");
    return {
      title: '香氛机',
      path: '/pages/index/index',
      imageUrl: '../../images/share.png'
    }
  },
  /**
     * 弹窗
     */
  showDialogBtn: function () {
    this.setData({
      showModal: true
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
  },
  getUserInfo: function (e) {
    console.log("---------userInfo----------")
    console.log(e)
    console.log("---------userInfo----------")
    if (e) {
      if (e.detail.errMsg == "getUserInfo:ok") {
        this.onConfirm();
        app.globalData.userInfo = e.detail.userInfo
        wx.setStorageSync('userInfo', e.detail.userInfo)
        this.setData({
          userInfo: e.detail.userInfo,
          hasUserInfo: true
        })
        //保存用户信息
        saveWeChatInfo(app.globalData)
      }
    }
  },
  onLoad: function () {
    var userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.onConfirm();
      console.log('-------local--------')
      console.log(userInfo)
      console.log('-------local--------')
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else {
      if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
        console.log("---1---");
        this.onConfirm();
        console.log("---1---");
        wx.setStorageSync('userInfo', app.globalData.userInfo)
      } else if (this.data.canIUse) {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userInfoReadyCallback = res => {
          wx.setStorageSync('userInfo', res.userInfo)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.onConfirm();
        }
      } else {
        // 在没有 open-type=getUserInfo 版本的兼容处理
        wx.getUserInfo({
          success: res => {
            this.onConfirm();
            app.globalData.userInfo = res.userInfo
            wx.setStorageSync('userInfo', res.userInfo)
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          }
        })
      }
    }
  },
  onShow: () => {

  }
})